"use strict";

const BaseController = require("./base");

// const marked = require("marked");

class ArticleController extends BaseController {
    async create() {
        const {ctx} = this;
        const {userId} = ctx.state;
        const {content, title, category, coverImage} = ctx.request.body;
        const obj = {
            title,
            article: content,
            // article_html: marked(content),
            author: userId,
            category,
            coverImage
        };
        let res = await ctx.model.Article.create(obj);
        if (res._id) {
            this.success({
                id: res._id,
                title: res.title,
            });
        } else {
            this.error("创建失败！");
        }
    }

    async getArticleList() {
        const {ctx} = this;
        let {page = 1, size = 5, keyword = ''} = ctx.query;
        const reg = new RegExp(keyword, 'i')
        //const list = await ctx.model.Article.find().populate("author").populate("category").sort({createdAt: -1});
        let [list, count] = await Promise.all([
            ctx.model.Article.find({$or: [{"title": {$regex: reg}}, {"article": {$regex: reg}}]})
                .populate("author").populate("category").limit(Number(size))
                .skip((page - 1) * size),
            ctx.model.Article.find({$or: [{"title": {$regex: reg}}, {"article": {$regex: reg}}]}).count()
        ])
        this.success({list, count});
    }

    async getArticleById() {
        const {ctx} = this;
        const {id} = ctx.params;
        const article = await ctx.model.Article.findOneAndUpdate(
            {_id: id},
            {$inc: {views: 1}}
        ).populate("author");
        this.success(article);
    }

    async getQiniuToken() {
        const {ctx} = this
        let uploadToken = await ctx.service.qiniu.getQiniuToken()
        this.success(uploadToken)
    }
}

module.exports = ArticleController;
